package com.szalay.desktopsearch.ui;

import com.szalay.desktopsearch.indexer.Fields;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import org.apache.solr.common.SolrDocument;

/**
 * Action to print an item.
 * @author szalay
 */
final class PrintItemAction extends AbstractAction {
    private static final long serialVersionUID = -5328639464366953346L;
    
    private final SolrDocument document;
    private final JPopupMenu parent;
    private final Desktop desktop = Desktop.getDesktop();
    
    PrintItemAction(SolrDocument document, JPopupMenu parent) {
        super("Print", new ImageIcon(PrintItemAction.class.getResource("/icons/print.png")));
        this.document = document;
        this.parent = parent;
    }

    @Override
    public boolean isEnabled() {
        return desktop.isSupported(Desktop.Action.PRINT);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        parent.setVisible(false);
        final String path = document.getFieldValue(Fields.PATH).toString();
        final File file = new File(path);
        try {
            desktop.print(file);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }    
}
